package com.cd.system.service.impl;

import com.cd.common.constant.LqqConstant;
import com.cd.common.domain.SysUser;
import com.cd.system.jpa.repository.UserRepository;
import com.cd.common.domain.LoginUser;
import com.cd.system.service.SysPermissionService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    @Qualifier("userDao")
    private UserRepository userDao;

    @Autowired
    private SysPermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        //mybatis+ 写法
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(User::getUserName,username);
//        User user = userMapper.selectOne(queryWrapper);
        //end
        SysUser user = userDao.selectUserByUserName(username);
        //如果没有查询到用户就抛出异常
        if (Objects.isNull(user)) {
            logger.error("校验失败");
            throw new RuntimeException(LqqConstant.USER_NAME_OR_PASSWORD_ERROR);
        }

        //Set<String> set=new HashSet<>();
        //权限添加
        //List<String> authority = userMapper.findAuthority(1L);
        //authority.forEach(set::add);

        //把数据封装成UserDetails返回
        //这边如果密码错误会被校验出来
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
